#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <filesystem>
#include <fstream>
#include <memory>
#include <time.h>
#include <cstdio>
#include <sstream>
#include <unistd.h>
#include "Mutex.hpp"
namespace LogModule
{
    using namespace LockModule;
    std::string CurrentTime()
    {
        time_t t = time(nullptr);
        struct tm curr;
        localtime_r(&t, &curr);
        char buff[64];
        snprintf(buff, sizeof buff, "%4d-%02d-%02d-%02d-%02d-%02d",
                 curr.tm_year+1900, curr.tm_mon+1, curr.tm_mday, curr.tm_hour, curr.tm_min, curr.tm_sec);
        return buff;
    }

    const std::string default_logpath = "./log/";
    const std::string default_logname = "log.txt";
    // 日志等级
    enum class LogLevel
    {
        DEBUG = 1, // 调试信息
        INFO,      // 正常信息
        WARING,
        ERROR,
        FATAL
    };
    std::string LevelTostring(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARING:
            return "WARING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "NONE";
        }
    }
    // 刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy() {}
        ~ConsoleLogStrategy() {}
        void SyncLog(const std::string &message)
        {
            LockGuard lockguard(_lock);
            std::cout << message << std::endl;
        }

    private:
        Mutex _lock;
    };
    class FileLogStrategy : public LogStrategy
    {
        public:
        FileLogStrategy(const std::string &logpath = default_logpath, const std::string &logname = default_logname)
            : _logpath(logpath), _logname(logname)
        {
            LockGuard lockguard(_lock);
            // 确认该文件是存在的
            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << std::endl;
            }
        }
        ~FileLogStrategy() {}
        void SyncLog(const std::string &message)
        {
            LockGuard lockguard(_lock);
            std::string log = _logpath + _logname;
            std::ofstream out(log, std::ios::app); // 日志写入是追加的
            if (!out.is_open())                    // 打开失败
            {
                return;
            }
            out << message << "\n";
            out.close();
        }

    private:
        std::string _logpath;
        std::string _logname;
        Mutex _lock;
    };
    // 日志类
    class Logger
    {
    public:
        Logger()
        {
            // 默认打印到显示器
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Logger() {}
        class LogMessage // 表示完整的一条日志信息
        //[2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16] - hello world
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, int line, Logger &logger)
                : _curr_time(CurrentTime()), _level(level), _filename(filename), _line(line), _pid(getpid()), _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "] "
                   << "[" << LevelTostring(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _filename << "] "
                   << "[" << _line << "] ";
                log_info = ss.str();
            }
            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                log_info += ss.str();
                return *this;
            }
            ~LogMessage()
            {
                if (_logger._strategy)
                    _logger._strategy->SyncLog(log_info);
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _filename;
            uint32_t _line;
            std::string log_info; // 一条完整的日志信息
            Logger &_logger;
        };
        LogMessage operator()(LogLevel level, const std::string &filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy; // 日志的刷新方案
    };
    Logger logger;
#define LOG(level) logger(level, __FILE__, __LINE__)
#define ENABLE_CONSOLO_LOG() logger.EnableConsoleLog()
#define ENABLE_FILE_LOG() logger.EnableFileLog()

}